package com.briup.server.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.briup.server.domain.bean.UserRole;
import com.briup.server.service.UserRoleService;
import com.briup.server.mapper.UserRoleMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole>
        implements UserRoleService {

    @Override
    @Transactional
    public void grantRolesToUser(Long userId, List<Long> roleIds) {
        // 无论该用户原有是否存在角色关联关系，一律先删除在分配新的角色关联关系
        remove(Wrappers.<UserRole>lambdaUpdate()
                .eq(UserRole::getUserId, userId));
        // 在批量绑定角色与用户之间的关系
        List<UserRole> list = roleIds.stream()
                .map(roleId -> {
                    UserRole userRole = new UserRole();
                    userRole.setUserId(userId);
                    userRole.setRoleId(roleId);
                    return userRole;
                })
                .toList();
        saveBatch(list);
    }
}




